package com.example.mybatisplus.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.service.PictureService;
import com.example.mybatisplus.model.domain.Picture;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.util.Base64;



/**
 *
 *  前端控制器
 *
 *
 * @author lxp
 * @since 2022-02-28
 * @version v1.0
 */
@Controller
@RequestMapping("/picture")
public class PictureController {

    private final Logger logger = LoggerFactory.getLogger(PictureController.class);

    @Autowired
    private PictureService pictureService;

    /**
     * 描述：根据Id 查询
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id) throws Exception {
        Picture picture = pictureService.getById(id);
        return JsonResponse.success(picture);
    }

    /**
     * 描述：根据Id删除
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        pictureService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
     * 描述：根据Id 更新
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updatePicture(@PathVariable("id") Long id, @RequestBody Picture picture) throws Exception {
        picture.setId(id);
        pictureService.updateById(picture);
        return JsonResponse.success(null);
    }


    /**
     * 描述:创建Picture
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(@RequestBody Picture picture) throws Exception {
        pictureService.save(picture);
        return JsonResponse.success(null);
    }
    @RequestMapping(value = "/addPicture", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Assert.notNull(file, "上传文件不能为空");
        String filePath = System.getProperty("user.dir") +
                "/src/main/resources/static/Picture/uploadFile/";//上传到这个文件夹
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        File file2 = new File(filePath);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        String savepath = filePath + "\\" + fileName;
        savepath = savepath.substring(savepath.lastIndexOf("/") + 1);
        savepath = savepath.replace("\\", "/");
        Map map = new HashMap<String, Object>();
        // String formerId = request.getParameter("formerId");
        String Faid = request.getParameter("id");
        long Fid = Long.parseLong(Faid);
        // long Fid = Long.parseLong(formerId);
        try {
            //保存文件到服务器
            System.out.println("測試1" + savepath);
            String realpath = file2.getPath() + "\\" + fileName;
            realpath = realpath.replace("\\", "/");
            System.out.println("測試2" + realpath);
            file.transferTo(new File(realpath));
            //保存到数据库
            System.out.println("測試3" + savepath);
            Picture pic = new Picture();
            pic.setActImage(savepath);
            pic.setId(Fid);
            QueryWrapper<Picture> wrapper = new QueryWrapper<>();
            wrapper.eq("id", Fid);
            Picture list1 = pictureService.getOne(wrapper);
            if (list1 == null) {
                pictureService.saveOrUpdate(pic);
            } else {
                pic.setId(list1.getId());
                pictureService.updateById(pic);
            }
            //返回json
            map.put("msg", "ok");
            map.put("code", 200);

        } catch (Exception e) {
            map.put("msg", "error");
            map.put("code", 0);
            e.printStackTrace();
        }
        return map;
    }
    @RequestMapping(value = "/getPicture/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse encodeBase64File(@PathVariable("id") Long id) throws Exception {
        Picture  picture =  pictureService.getById(id);
        String filename = picture.getActImage();
        String filepath =  System.getProperty("user.dir") +
                "/src/main/resources/static/Picture/uploadFile/" + filename;
        filepath = filepath.replace("\\", "/");
        System.out.println(filepath);
        File file = new File(filepath);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();

        return JsonResponse.success( Base64.getEncoder().encode(buffer),filename);
    }
}


